from django.db import models
from django.contrib.auth.models import AbstractBaseUser
from django.db.models import F


# Create your models here.
# RBAC权限模型


class UserInfo(AbstractBaseUser):
    """
    用户表
    """
    username = models.CharField(max_length=32, null=False, blank=False, help_text='用户名', unique=True)
    password = models.CharField(max_length=128, null=False, blank=False, help_text='密码')
    email = models.EmailField(null=False, blank=False, unique=True, default=True, help_text="用户邮箱")
    is_enabled = models.BooleanField(default=True, help_text="是否启用账号，默认为True")
    last_login = models.DateTimeField(auto_now=True, blank=True, null=True, help_text="最后一次登录时间")
    created_at = models.DateTimeField(auto_now_add=True, help_text='注册时间')
    # 与role 表为多对多的关系，使用ManyToManyField会自动生成关系表
    roles = models.ManyToManyField("Role")
    # 必须要写,要否则会报 AttributeError: type object 'UserInfo' has no attribute 'USERNAME_FIELD'
    USERNAME_FIELD = 'username'

    def __str__(self):
        return self.username

    class Meta:
        db_table = 'rbac_user'
        verbose_name = '用户'
        verbose_name_plural = '用户'


class Role(models.Model):
    """
    角色表
    """
    name = models.CharField(max_length=18, null=False, unique=True, blank=False, help_text='角色名称')
    created_at = models.DateTimeField(auto_now_add=True, help_text='注册时间')
    update_at = models.DateTimeField(auto_now=True, help_text='更新时间')
    # 与permission 表为多对多的关系，使用ManyToManyField会自动生成关系表
    permissions = models.ManyToManyField("Permission")

    def __str__(self):
        return self.name

    class Meta:
        db_table = 'rbac_role'


class Permission(models.Model):
    """
    权限表
    """
    name = models.CharField(max_length=48, null=False, blank=False, unique=True, help_text="接口名称")
    url_name = models.CharField(max_length=64, null=False, blank=False, help_text="url别名，需要与url.py中统一")
    method = models.CharField(max_length=10, null=False, blank=False,
                              help_text="url请求method：【 'GET','POST','PUT','DELETE'] 可以以列表形式写单个或多个")
    is_menu = models.BooleanField(default=False, help_text="是否为菜单，在mysql中，1为True,0为False")
    sort = models.CharField(max_length=100, default=-1, help_text="菜单排序用，默认为-1，数字越大越靠后")
    parent = models.ForeignKey("Permission", null=True, blank=True, on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True, help_text='注册时间')
    update_at = models.DateTimeField(auto_now=True, editable=False, help_text='更新时间')

    def __str__(self):
        # 显示层级菜单
        title_list = [self.name]
        p = self.parent
        while p:
            title_list.insert(0, p.name)
            p = p.parent
        return '-'.join(title_list)

    class Meta:
        db_table = 'rbac_permission'


# 获取role和permission 树关系
def get_permission_tree():
    permission_parent = Permission.objects.filter(is_menu=True, parent=None)
    json_data = []

    for parent in range(0, permission_parent.count()):
        now_data = permission_parent[parent]
        id = now_data.id
        title = now_data.name
        children_list = Permission.objects.filter(parent=id).values('id', title=F('name'))
        children = list(children_list)
        d = {
            'id': id,
            'title': title,
            'children': children
        }
        json_data.append(d)
    # 其余权限放到other分组
    other = {
        'id': 9999,
        'title': '其他',
        'children': list(Permission.objects.filter(is_menu=False, parent=None).values('id', title=F('name')))
    }
    json_data.append(other)

    return json_data
